const jwt = require('jsonwebtoken');
const config = require('../config');
const User = require('../models/user.model');
const ApiError = require('../utils/ApiError');

const auth = (...requiredRoles) => {
  return async (req, res, next) => {
    try {
      console.log("auth called");
      // 1. 获取token
      const token = req.headers.authorization?.split(' ')[1];
      console.log("auth called: ",token);
      if (!token) throw new ApiError(401, 'Authentication required');

      // 2. 验证token
      const decoded = jwt.verify(token, config.jwt.secret);
      
      // 3. 获取用户信息
      const user = await User.findUserById(decoded.id);
      console.log("auth called: ",user, decoded.id);
      if (!user) throw new ApiError(401, 'User not found');
      
      // 4. 检查账号状态
      // if (!user.isActive) throw new ApiError(401, 'Account is disabled');
      
      // 5. 检查角色权限
      console.log(requiredRoles);
      if (requiredRoles.length && !requiredRoles.includes(user.role)) {
        throw new ApiError(403, 'Forbidden');
      }

      // 6. 附加用户信息到请求对象
      req.user = user;
      next();
    } catch (error) {
      next(error);
    }
  };
};

module.exports = auth;